# -*- coding: utf-8 -*-
import scrapy, urllib
from scrapy.http import Request, FormRequest
import ssl

ssl._create_default_https_context = ssl._create_unverified_context

class DoubanloginSpider(scrapy.Spider):
    name = 'DoubanLogin'
    allowed_domains = ['douban.com']
    start_urls = ['http://douban.com/']
    header = {
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/604.5.2 (KHTML, like Gecko) Version/11.0.3 Safari/604.5.2",
        "Referer": "https://www.douban.com/"}

    def start_requests(self):
        return [Request(url="https://www.douban.com/accounts/login", headers=self.header, meta={"cookiejar":1},callback=self.parse)]
        # d=self.data()
        #
        # return [FormRequest(formdata=d,url="https://www.douban.com/accounts/login", headers=self.header, meta={"cookiejar":1},callback=self.parse)]


    def data(self, cs="",cid=""):
        d = {
            "source": "index_nav",
            "form_email": "",
            "form_password": ""
        }
        if (cs):
            d["captcha-id"]=cid;
            d["captcha-solution"]=cs;
            d["redir"]="https://www.douban.com"
            d["login"]="登录"
        print(d)
        return d

    def parse(self, response):
        validatestr = response.xpath("//img[@id='captcha_image']/@src").extract()
        vid = response.xpath("//input[@name='captcha-id']/@value").extract()[0]
        if(validatestr):
            data = urllib.request.urlopen(validatestr[0]).read()
            f = open("validate.jpg", "wb")
            f.write(data)
            f.close()
            a=input("验证码:")
            return [FormRequest(formdata=self.data(cs=a,cid = vid),url="https://accounts.douban.com/login", headers=self.header, meta={"cookiejar":True},callback=self.next)]
        else:
            return self.next(response)

    def next(self,response):
        return Request("https://www.douban.com/accounts/",headers=self.header, meta={"cookiejar":True},callback=self.homepage)

    def homepage(self,response):
        print(response.body)
        validatestr = response.xpath("//img[@id='captcha_image']/@src").extract()
        if (validatestr):
            return self.parse(response)
        print(response.xpath("//span/text()").extract())
